<template>
  <div class="chat-container">
    <div class="chat-header">
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index"
        :class="['message', message.role === 'user' ? 'user-message' : (message.isResult ? 'result-message' : 'ai-message')]">
        <div class="message-avatar">
          <el-avatar :icon="message.role === 'user' ? 'User' : (message.isResult ? 'Document' : 'ChatDotRound')" />
        </div>

        <!-- 结果消息内容 -->
        <div v-if="message.isResult" class="result-content-wrapper">
          <div class="result-header">
            <el-icon>
              <Document />
            </el-icon>
            <span>处理结果</span>
          </div>
          <div class="result-content">
            <div v-html="formatMessage(message)"></div>
            <div class="result-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>

        <!-- 普通消息内容 -->
        <div v-else class="message-content">
          <div class="message-text" v-html="formatMessage(message)"></div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div class="tools-bar">
        <div v-for="tool in tools" :key="tool.id" class="tool-item" @click="insertTool(tool)">
          <el-icon>
            <component :is="tool.icon"></component>
          </el-icon>
          <span>{{ tool.name }}</span>
        </div>
      </div>

      <div class="input-container" @dragover.prevent @drop="onDropWorkflow($event)">
        <!-- 显示选中的工具或工作流 -->
        <div v-if="selectedTools.length > 0 || selectedWorkflows.length > 0 || selectedMCPTools.length > 0"
          class="selected-item">
          <div v-for="tool in selectedTools" :key="tool.id" class="tool-button">
            <el-icon>
              <component :is="tool.icon"></component>
            </el-icon>
            <span>{{ tool.name }}</span>
            <el-icon class="remove-single-item" @click="removeTool(tool.id)">
              <Close />
            </el-icon>
          </div>
          <div v-for="workflow in selectedWorkflows" :key="workflow.id" class="workflow-button">
            <div class="workflow-icon">
              <el-icon>
                <component :is="workflow.icon"></component>
              </el-icon>
            </div>
            <span>{{ workflow.name }}</span>
            <el-icon class="remove-single-item" @click="removeWorkflow(workflow.id)">
              <Close />
            </el-icon>
          </div>
          <div v-for="mcpTool in selectedMCPTools" :key="mcpTool.id" class="mcp-tool-button">
            <div class="mcp-tool-icon">
              <el-icon>
                <component :is="mcpTool.icon"></component>
              </el-icon>
            </div>
            <span>{{ mcpTool.name }}</span>
            <el-icon class="remove-single-item" @click="removeMCPTool(mcpTool.id)">
              <Close />
            </el-icon>
          </div>
          <el-icon class="remove-all-items" @click="clearAllSelections">
            <Delete />
          </el-icon>
        </div>

        <el-input v-model="userInput" type="textarea" :rows="3" placeholder="输入您的问题，或拖入工具组件..." resize="none"
          @keydown.enter.prevent="sendMessage" :disabled="isLoading" />
      </div>

      <div class="input-actions">
        <div v-if="isLoading" class="thinking-indicator">
          <span>AI正在思考中</span>
          <div class="dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        <el-button type="primary" @click="sendMessage"
          :disabled="isLoading || (userInput.trim() === '' && selectedTools.length === 0 && selectedWorkflows.length === 0 && selectedMCPTools.length === 0)">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Ref } from 'vue';
import { nextTick, onMounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { marked } from 'marked';
import hljs from 'highlight.js';
import { Close, Delete, Document } from '@element-plus/icons-vue';
import store from '@/store';

// 生成一个固定的会话ID
const sessionId = ref(`user_${Date.now()}`);

interface Tool {
  id: string;
  name: string;
  icon: string;
}

interface Workflow {
  id: string;
  name: string;
  icon: string;
  description?: string;
}

interface MCPTool {
  id: string;
  name: string;
  icon: string;
  description: string;
  type: string;
}

// 选中的工作流数组
const selectedWorkflows = ref<Workflow[]>([]);

// 选中的工具数组
const selectedTools = ref<Tool[]>([]);

// 选中的MCP工具数组
const selectedMCPTools = ref<MCPTool[]>([]);

// 移除流式模式变量
// const useStreamMode = ref(true);

// 在输入框中拖拽工作流或工具
const onDropWorkflow = (event: DragEvent): void => {
  event.preventDefault();

  console.log('拖拽事件触发:', event);
  console.log('可用数据类型:', event.dataTransfer?.types);

  if (event.dataTransfer) {
    try {
      let draggedItem: Tool | Workflow | MCPTool | any = null;
      let itemType = '';

      // 获取dataTransfer中的所有可用类型
      const availableTypes = event.dataTransfer.types;
      console.log('可用数据类型:', availableTypes);

      // 尝试读取工作流数据
      if (availableTypes.includes('application/workflow')) {
        const workflowData = event.dataTransfer.getData('application/workflow');
        console.log('工作流数据:', workflowData);
        if (workflowData) {
          draggedItem = JSON.parse(workflowData);
          itemType = 'workflow';
          console.log('解析后的工作流:', draggedItem);

          // 检查是否已经存在相同ID的工作流
          if (!selectedWorkflows.value.some(item => item.id === draggedItem.id)) {
            selectedWorkflows.value.push(draggedItem as Workflow);
            ElMessage.success(`已添加工作流: ${draggedItem.name}`);
          } else {
            ElMessage.warning(`工作流已存在: ${draggedItem.name}`);
          }
        }
      }

      // 尝试读取快捷工具数据
      else if (availableTypes.includes('application/quick-tool')) {
        const quickToolData = event.dataTransfer.getData('application/quick-tool');
        console.log('工具数据:', quickToolData);
        if (quickToolData) {
          draggedItem = JSON.parse(quickToolData);
          itemType = 'quickTool';
          console.log('解析后的工具:', draggedItem);

          // 检查是否已经存在相同ID的工具
          if (!selectedTools.value.some(item => item.id === draggedItem.id)) {
            selectedTools.value.push(draggedItem as Tool);
            ElMessage.success(`已添加工具: ${draggedItem.name}`);
          } else {
            ElMessage.warning(`工具已存在: ${draggedItem.name}`);
          }
        }
      }

      // 尝试读取MCP工具数据
      else if (availableTypes.includes('application/mcp-tool')) {
        const mcpToolData = event.dataTransfer.getData('application/mcp-tool');
        console.log('MCP数据:', mcpToolData);
        if (mcpToolData) {
          draggedItem = JSON.parse(mcpToolData);
          itemType = 'mcpTool';
          console.log('解析后的MCP工具:', draggedItem);

          // 检查是否已经存在相同ID的MCP工具
          if (!selectedMCPTools.value.some(item => item.id === draggedItem.id)) {
            selectedMCPTools.value.push(draggedItem as MCPTool);
            ElMessage.success(`已添加MCP组件: ${draggedItem.name}`);
          } else {
            ElMessage.warning(`MCP组件已存在: ${draggedItem.name}`);
          }
        }
      }

      // 尝试读取文本数据
      else if (availableTypes.includes('text/plain')) {
        const textData = event.dataTransfer.getData('text/plain');
        console.log('文本数据:', textData);
        try {
          draggedItem = JSON.parse(textData);
          itemType = 'text';
          console.log('解析后的文本数据:', draggedItem);
        } catch (e) {
          console.log('非JSON格式的文本数据');
        }
      }

      // 如果有工具ID，将其添加到store
      if (draggedItem && draggedItem.id) {
        console.log('准备向store添加ID:', draggedItem.id);
        // 将智能体ID添加到store中
        try {
          store.dispatch('setSelectedAgentIds', [draggedItem.id]);
          console.log('已向store添加ID:', draggedItem.id);

          // 显示成功提示（如果还没有显示过）
          if (itemType === 'text') {
            ElMessage.success(`已选择智能体: ${draggedItem.name || draggedItem.id}`);
          }

          // 不再自动显示右侧文档栏
          // store.dispatch('showRightSidebar');
          // console.log('已显示右侧文档栏');
        } catch (storeError) {
          console.error('store操作失败:', storeError);
        }
      }
    } catch (error) {
      console.error('解析拖拽数据失败:', error);
    }
  }
};

// 定义工具列表
const tools = ref<Tool[]>([
  { id: 'upload-file', name: '上传文件', icon: 'Upload' }
]);

// 在输入框中插入工具按钮
const insertTool = (tool: Tool): void => {
  // 根据选中的工具调用页面
  selectedTools.value.push(tool);
};

interface ChatMessage {
  role: 'user' | 'ai';
  content: string;
  timestamp: Date;
  tool?: Tool | null;
  workflow?: Workflow | null;
  mcpTool?: MCPTool | null;
  isResult?: boolean;
  resultId?: string;
}

// 配置marked使用highlight.js进行代码高亮
// 使用marked的扩展机制进行代码高亮
marked.use({
  renderer: {
    code(code, language) {
      const validLanguage = language && hljs.getLanguage(language) ? language : 'plaintext';
      return `<pre><code class="hljs language-${validLanguage}">${hljs.highlight(code, { language: validLanguage }).value
        }</code></pre>`;
    },
    table(header, body) {
      return `<table class="markdown-table">
        <thead>${header}</thead>
        <tbody>${body}</tbody>
      </table>`;
    },
    blockquote(quote) {
      return `<blockquote class="markdown-blockquote">${quote}</blockquote>`;
    },
    list(body, ordered) {
      const type = ordered ? 'ol' : 'ul';
      return `<${type} class="markdown-list">${body}</${type}>`;
    }
  },
  breaks: true, // 将换行符转换为<br>标签
  gfm: true    // 启用GitHub风格的Markdown
});

const userInput = ref('');
const messages: Ref<ChatMessage[]> = ref([
  {
    role: 'ai',
    content: '你好！我是WendAI，有什么我可以帮助你的吗？',
    timestamp: new Date()
  }
]);
const isLoading = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);

// 滚动到底部
const scrollToBottom = (): void => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
});

onMounted(() => {
  scrollToBottom();
});

// 在script部分添加一个变量来存储当前的流式结果消息
const currentStreamingResult = ref<ChatMessage | null>(null);
// 添加一个结果消息索引
const currentResultMessageIndex = ref<number | null>(null);

// 添加一个创建新结果消息的辅助函数
const createNewResultMessage = (content: string, timestamp: Date, resultId?: string): number => {
  const newResultMessage: ChatMessage = {
    role: 'ai',
    isResult: true,
    content: content,
    timestamp: timestamp,
    resultId: resultId || `result_${Date.now()}`
  };
  messages.value.push(newResultMessage);
  currentStreamingResult.value = newResultMessage;
  currentResultMessageIndex.value = messages.value.length - 1;
  return currentResultMessageIndex.value;
};

// 添加重置结果消息状态的函数
const resetResultMessageState = (): void => {
  currentStreamingResult.value = null;
  currentResultMessageIndex.value = null;
};

// 修改sendStreamRequest函数中处理结果消息的部分
const sendStreamRequest = async (
  userMessage: string,
  tools: string[][],
  sessionId: string,
  aiMessageIndex: number
): Promise<void> => {
  try {
    // 设置请求超时
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 60000); // 60秒超时

    // 使用流式API
    console.log('准备发送请求到流式API', {
      message: userMessage,
      tools: tools,
      session_id: sessionId
    });

    // 初始化响应
    messages.value[aiMessageIndex].content = '正在思考...';

    const response = await fetch('/api/chat/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: JSON.stringify({
        message: userMessage,
        tools: tools,
        session_id: sessionId
      }),
      mode: 'cors',
      credentials: 'same-origin',
      cache: 'no-cache',
      signal: controller.signal
    });

    clearTimeout(timeoutId); // 请求成功，清除超时

    // 更新AI消息内容
    if (response.ok && response.body && aiMessageIndex < messages.value.length) {
      console.log('收到流式API响应:', response);

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let receivedFirstChunk = false;
      let fullResponse = '';

      // 添加接收超时检测
      let lastReceiveTime = Date.now();
      const receiveTimeoutMs = 60000; // 60秒超时
      const checkReceiveTimeout = setInterval(() => {
        const now = Date.now();
        if (now - lastReceiveTime > receiveTimeoutMs) {
          console.warn('接收数据超时');
          clearInterval(checkReceiveTimeout);
          reader.cancel('超时取消').catch(e => console.error('取消读取器失败', e));

          // 在消息中添加超时提示
          if (receivedFirstChunk) {
            messages.value[aiMessageIndex].content += '\n\n[连接超时，等待服务器响应...]';
          } else {
            // 如果还没收到第一个响应，保留"正在思考"，但添加超时提示
            messages.value[aiMessageIndex].content += '\n\n[连接超时，等待服务器响应...]';
          }
        }
      }, 5000); // 每5秒检查一次

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          lastReceiveTime = Date.now();
          const chunkText = decoder.decode(value, { stream: true });

          if (chunkText.trim()) {
            try {
              const jsonObjects = splitJsonObjects(chunkText);

              for (const jsonStr of jsonObjects) {
                if (!jsonStr.trim()) continue;

                try {
                  const responseData = JSON.parse(jsonStr);
                  // 处理消息，区分 message 和 result 类型
                  if (responseData.type === 'message') {
                    // 如果是第一个消息，清除"正在思考"提示
                    if (!receivedFirstChunk) {
                      receivedFirstChunk = true;
                      fullResponse = '';
                    }

                    // 根据内容类型显示消息
                    if (responseData.type === 'message' && responseData.content) {
                      console.log('收到message 流式消息:', responseData);
                      // 如果消息内容是对象，尝试解析和格式化
                      if (typeof responseData.content === 'object') {
                        // 处理各种对象格式
                        if (responseData.content.status === 'error') {
                          fullResponse += responseData.content.message || responseData.content.content || JSON.stringify(responseData.content);
                        } else if (responseData.content.content) {
                          fullResponse += responseData.content.content;
                        } else {
                          fullResponse += JSON.stringify(responseData.content, null, 2);
                        }
                      } else {
                        // 直接使用字符串内容
                        fullResponse += responseData.content;
                      }

                      messages.value[aiMessageIndex].content = fullResponse;
                    }
                  } else if (responseData.type === 'result') {
                    console.log('收到result 流式结果消息:', responseData);
                    
                    // 获取结果ID，如果没有则使用默认值
                    const resultId = responseData.resultId || 'default_result';
                    
                    // 检查是否需要创建新结果消息
                    // 如果是新的结果ID或者首次收到结果，则创建新消息
                    if (!currentStreamingResult.value || 
                        currentResultMessageIndex.value === null || 
                        (currentStreamingResult.value.resultId !== resultId)) {
                      // 如果resultId不同，创建新的结果消息
                      createNewResultMessage(responseData.content, new Date(responseData.timestamp), resultId);
                    } else {
                      // 更新现有结果消息的内容
                      messages.value[currentResultMessageIndex.value].content += responseData.content;
                    }
                  } else if (responseData.error === true) {
                    // 获取错误ID，如果没有则使用默认值
                    const errorId = responseData.errorId || 'default_error';
                    
                    // 检查是否需要创建新错误消息
                    if (!currentStreamingResult.value || 
                        currentResultMessageIndex.value === null || 
                        (currentStreamingResult.value.resultId !== errorId)) {
                      // 如果resultId不同，创建新的错误消息
                      createNewResultMessage(responseData.content, new Date(responseData.timestamp), errorId);
                    } else {
                      // 更新现有错误消息的内容
                      messages.value[currentResultMessageIndex.value].content += responseData.content;
                    }
                  }
                } catch (innerErr) {
                  console.error('解析单个JSON对象失败:', innerErr, jsonStr);
                }
              }

              // 滚动到底部
              nextTick(() => {
                scrollToBottom();
              });
            } catch (parseErr) {
              console.error('解析JSON响应失败:', parseErr, 'Raw chunk:', chunkText);
              // 如果不是有效的JSON，将其作为文本追加
              if (!receivedFirstChunk) {
                receivedFirstChunk = true;
                fullResponse = ''; // 清除"正在思考"消息
              }
              fullResponse += chunkText;
              messages.value[aiMessageIndex].content = fullResponse;

              // 滚动到底部
              nextTick(() => {
                scrollToBottom();
              });
            }
          }
        }

        // 清除超时检查
        clearInterval(checkReceiveTimeout);

        // 如果没有接收到任何数据，保留"正在思考"消息，但添加提示
        if (!receivedFirstChunk) {
          messages.value[aiMessageIndex].content += '\n\n未收到任何响应数据，请重试。';
        }
      } catch (streamErr) {
        console.error('读取流数据时出错:', streamErr);

        // 清除超时检查
        clearInterval(checkReceiveTimeout);

        const errorMessage = streamErr instanceof Error ? streamErr.message : '未知错误';
        // 添加错误提示
        messages.value[aiMessageIndex].content += `\n\n[读取数据时出错: ${errorMessage}]`;
      }
    } else {
      // 请求失败
      const statusCode = response?.status || '未知';
      const statusText = response?.statusText || '未知原因';
      console.error('流式API请求失败:', statusCode, statusText);
      messages.value[aiMessageIndex].content = `请求失败，状态码: ${statusCode}，原因: ${statusText}`;
    }

    isLoading.value = false;
  } catch (error) {
    console.error('获取流式AI回复失败:', error);
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    ElMessage.error(`获取回复失败: ${errorMessage}`);

    // 更新为错误消息，保留"正在思考"的提示
    if (aiMessageIndex < messages.value.length) {
      messages.value[aiMessageIndex].content += `\n\n抱歉，我遇到了一些问题，无法回复您的消息。\n错误详情: ${errorMessage}\n请稍后再试。`;
    }

    // 重置结果消息状态
    resetResultMessageState();
    isLoading.value = false;
  }
};

// 修改clearAllSelections函数，确保清除流式状态
const clearAllSelections = (): void => {
  if (selectedTools.value.length > 0 || selectedWorkflows.value.length > 0 || selectedMCPTools.value.length > 0) {
    selectedTools.value = [];
    selectedWorkflows.value = [];
    selectedMCPTools.value = [];
    resetResultMessageState(); // 清除结果消息状态
    updateSessionId();
  }
};

// 移除特定的工具
const removeTool = (toolId: string): void => {
  selectedTools.value = selectedTools.value.filter(tool => tool.id !== toolId);
  // 更新会话ID，让后端忘记这个工具的历史
  updateSessionId();
};

// 移除特定的工作流
const removeWorkflow = (workflowId: string): void => {
  selectedWorkflows.value = selectedWorkflows.value.filter(workflow => workflow.id !== workflowId);
  // 更新会话ID，让后端忘记这个工作流的历史
  updateSessionId();
};

// 移除特定的MCP工具
const removeMCPTool = (mcpToolId: string): void => {
  selectedMCPTools.value = selectedMCPTools.value.filter(mcpTool => mcpTool.id !== mcpToolId);
  // 更新会话ID，让后端忘记这个MCP工具的历史
  updateSessionId();
};

// 更新会话ID
const updateSessionId = (): void => {
  // 生成新的会话ID
  sessionId.value = `user_${Date.now()}`;
  console.log('会话ID已更新:', sessionId.value);
  
  // 重置结果消息状态
  resetResultMessageState();

  // 可选：添加提示
  ElMessage.info('已重置会话状态');
};

// 格式化消息内容，支持工具、工作流和MCP工具显示
const formatMessage = (message: ChatMessage): string => {
  let content = marked(message.content);

  if (message.tool) {
    // 如果消息包含工具，添加工具按钮HTML
    const toolHtml = `
      <div class="tool-tag">
        <span class="tool-id" style="display:none">${message.tool.id}</span>
      </div>
    `;
    content += toolHtml;
  }

  if (message.workflow) {
    // 如果消息包含工作流，添加工作流按钮HTML
    const workflowHtml = `
      <div class="workflow-tag">
        <span class="workflow-icon"></span>
        <span class="workflow-id" style="display:none">${message.workflow.id}</span>
      </div>
    `;
    content += workflowHtml;
  }

  if (message.mcpTool) {
    // 如果消息包含MCP工具，添加MCP工具按钮HTML
    const mcpToolHtml = `
      <div class="mcp-tool-tag">
        <span class="mcp-tool-id" style="display:none">${message.mcpTool.id}</span>
      </div>
    `;
    content += mcpToolHtml;
  }

  return content;
};

// 格式化时间
const formatTime = (timestamp: Date): string => {
  return new Date(timestamp).toLocaleTimeString();
};

// 添加一个用于分割多个JSON对象的辅助函数
const splitJsonObjects = (text: string): string[] => {
  const result: string[] = [];
  let bracketCount = 0;
  let start = 0;

  for (let i = 0; i < text.length; i++) {
    if (text[i] === '{') {
      if (bracketCount === 0) {
        start = i;
      }
      bracketCount++;
    } else if (text[i] === '}') {
      bracketCount--;
      if (bracketCount === 0) {
        result.push(text.substring(start, i + 1));
      }
    }
  }

  // 如果没有找到完整的JSON对象，返回原始文本
  if (result.length === 0 && text.trim()) {
    result.push(text);
  }

  return result;
};

// 发送消息函数
const sendMessage = async (): Promise<void> => {
  if ((!userInput.value.trim() &&
    selectedTools.value.length === 0 &&
    selectedWorkflows.value.length === 0 &&
    selectedMCPTools.value.length === 0) ||
    isLoading.value) return;

  let messageContent = userInput.value;
  let toolIds = selectedTools.value.map(tool => tool.id);
  let workflowIds = selectedWorkflows.value.map(workflow => workflow.id);
  let mcpToolIds = selectedMCPTools.value.map(mcpTool => mcpTool.id);

  // 如果选择了工具，添加工具信息
  if (selectedTools.value.length > 0) {
    toolIds = selectedTools.value.map(tool => tool.id);
    // 如果用户没有输入内容，使用默认消息
    if (!messageContent.trim()) {
      messageContent = `使用工具: ${selectedTools.value.map(tool => tool.name).join(', ')}`;
    }
  }

  // 如果选择了工作流，添加工作流信息
  if (selectedWorkflows.value.length > 0) {
    workflowIds = selectedWorkflows.value.map(workflow => workflow.id);
    // 如果用户没有输入内容，使用默认消息
    if (!messageContent.trim()) {
      messageContent = `执行工作流: ${selectedWorkflows.value.map(workflow => workflow.name).join(', ')}`;
    }
  }

  // 如果选择了MCP工具，添加MCP工具信息
  if (selectedMCPTools.value.length > 0) {
    mcpToolIds = selectedMCPTools.value.map(mcpTool => mcpTool.id);
    // 如果用户没有输入内容，使用默认消息
    if (!messageContent.trim()) {
      messageContent = `使用MCP组件: ${selectedMCPTools.value.map(mcpTool => mcpTool.name).join(', ')}`;
    }
  }

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: messageContent,
    timestamp: new Date(),
    tool: selectedTools.value.length > 0 ? selectedTools.value[0] : undefined,
    workflow: selectedWorkflows.value.length > 0 ? selectedWorkflows.value[0] : undefined,
    mcpTool: selectedMCPTools.value.length > 0 ? selectedMCPTools.value[0] : undefined
  });

  // 清空输入框
  userInput.value = '';
  const userMessage = messageContent;
  const userTools = selectedTools.value;
  const userWorkflows = selectedWorkflows.value;
  const userMCPTools = selectedMCPTools.value;

  // 滚动到底部
  await nextTick();
  scrollToBottom();

  // 显示加载状态
  isLoading.value = true;
  
  // 重置结果消息状态，确保每次新消息发送都能收到新的结果
  resetResultMessageState();

  // 添加临时AI消息占位
  const aiMessageIndex = messages.value.length;
  messages.value.push({
    role: 'ai',
    content: '正在进行思考...',
    timestamp: new Date()
  });

  // 使用流式请求处理
  await sendStreamRequest(userMessage, [toolIds, workflowIds, mcpToolIds], sessionId.value, aiMessageIndex);
};

</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background: linear-gradient(120deg, #F9FAFB 0%, #F1F5F9 100%);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.chat-header {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid #EEE;
}

/* 移除流式模式切换相关样式 */
/* .stream-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.85rem;
  color: #64748B;
} */

/* 创建通用滚动条样式类，可以应用到所有需要滚动的元素 */
.custom-scrollbar {
  scrollbar-width: thin;
  /* Firefox */
  scrollbar-color: rgba(139, 92, 246, 0.3) transparent;
  /* Firefox */
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background-color: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(139, 92, 246, 0.3);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(139, 92, 246, 0.5);
}

/* 聊天消息容器 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  background-image: radial-gradient(circle at 10% 20%, rgba(236, 72, 153, 0.03) 0%, transparent 20%),
    radial-gradient(circle at 80% 50%, rgba(99, 102, 241, 0.04) 0%, transparent 25%),
    radial-gradient(circle at 40% 70%, rgba(16, 185, 129, 0.03) 0%, transparent 30%);
}

/* 替代原有的独立滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background-color: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(139, 92, 246, 0.3);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background-color: rgba(139, 92, 246, 0.5);
}

/* 为常用工作流区域应用通用滚动条样式 */
.workflow-list {
  max-height: 300px;
  overflow-y: auto;
}

.workflow-list::-webkit-scrollbar {
  width: 6px;
}

.workflow-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.workflow-list::-webkit-scrollbar-thumb {
  background-color: rgba(139, 92, 246, 0.3);
  border-radius: 3px;
}

.workflow-list::-webkit-scrollbar-thumb:hover {
  background-color: rgba(139, 92, 246, 0.5);
}

.message {
  display: flex;
  margin-bottom: 1.2rem;
  max-width: 80%;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  margin: 0 0.7rem;
}

.message-avatar .el-avatar {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 2px solid white;
}

.user-message .message-avatar .el-avatar {
  background: linear-gradient(45deg, #8B5CF6 0%, #6366F1 100%);
}

.ai-message .message-avatar .el-avatar {
  background: linear-gradient(45deg, #10B981 0%, #059669 100%);
}

.message-content {
  background-color: white;
  padding: 0.9rem 1.2rem;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.06);
  position: relative;
  overflow: hidden;
}

.message-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #10B981 0%, #6366F1 100%);
  opacity: 0.5;
}

.user-message .message-content {
  background: linear-gradient(135deg, #8B5CF6 0%, #6366F1 100%);
  color: white;
}

.user-message .message-content::before {
  background: white;
  opacity: 0.2;
}

.message-text {
  word-break: break-word;
  line-height: 1.5;
}

.message-text :deep(pre) {
  background-color: #1E293B;
  border-radius: 8px;
  padding: 1rem;
  overflow-x: auto;
  margin: 0.8rem 0;
  position: relative;
}

.message-text :deep(code) {
  font-family: 'Fira Code', monospace;
}

.message-text :deep(p code) {
  background-color: #f1f5f9;
  color: #1e293b;
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  font-size: 0.9em;
}

.user-message .message-text :deep(pre) {
  background-color: rgba(0, 0, 0, 0.2);
}

.message-text :deep(.markdown-blockquote) {
  border-left: 4px solid #6366F1;
  padding-left: 1rem;
  margin: 1rem 0;
  color: #64748b;
  font-style: italic;
}

.message-text :deep(.markdown-table) {
  border-collapse: collapse;
  width: 100%;
  margin: 1rem 0;
  overflow-x: auto;
  display: block;
}

.message-text :deep(.markdown-table th),
.message-text :deep(.markdown-table td) {
  border: 1px solid #e2e8f0;
  padding: 0.6rem 1rem;
  text-align: left;
}

.message-text :deep(.markdown-table th) {
  background-color: #f1f5f9;
  font-weight: 600;
}

.message-text :deep(.markdown-table tr:nth-child(even)) {
  background-color: #f8fafc;
}

.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3),
.message-text :deep(h4),
.message-text :deep(h5),
.message-text :deep(h6) {
  margin-top: 1.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
  line-height: 1.25;
  color: #1e293b;
}

.message-text :deep(h1) {
  font-size: 1.5rem;
}

.message-text :deep(h2) {
  font-size: 1.35rem;
}

.message-text :deep(h3) {
  font-size: 1.2rem;
}

.message-text :deep(h4) {
  font-size: 1.1rem;
}

.message-text :deep(h5) {
  font-size: 1rem;
}

.message-text :deep(h6) {
  font-size: 0.9rem;
}

.message-text :deep(a) {
  color: #3b82f6;
  text-decoration: none;
  transition: all 0.2s ease;
}

.message-text :deep(a:hover) {
  text-decoration: underline;
  color: #2563eb;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  padding-left: 1.5rem;
  margin: 1rem 0;
}

.message-text :deep(li) {
  margin-bottom: 0.5rem;
}

.message-text :deep(hr) {
  border: 0;
  border-top: 1px solid #e2e8f0;
  margin: 1.5rem 0;
}

.message-text :deep(img) {
  max-width: 100%;
  border-radius: 4px;
  margin: 1rem 0;
}

.message-time {
  font-size: 0.75rem;
  color: #94A3B8;
  margin-top: 0.5rem;
  text-align: right;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* 添加工具栏样式 */
.tools-bar {
  display: flex;
  gap: 0.8rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid #E5E7EB;
  margin-bottom: 0.8rem;
}

.tool-item {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.4rem 0.8rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tool-item:hover {
  background-color: #F1F5F9;
}

.tool-item .el-icon {
  font-size: 1.1rem;
  color: #6366F1;
}

.tool-button {
  display: flex;
  align-items: center;
  padding: 0.4rem 0.8rem;
  background-color: #F1F5F9;
  border-radius: 6px;
  color: #3B82F6;
  font-size: 0.9rem;
  position: relative;
  border: 1px solid #E2E8F0;
}

.tool-button .el-icon {
  margin-right: 0.4rem;
}

.remove-tool {
  cursor: pointer;
  color: #94A3B8;
  transition: color 0.2s ease;
}

.remove-tool:hover {
  color: #EF4444;
}

.input-container {
  margin-bottom: 0.8rem;
}

.message-text .tool-button {
  display: inline-flex;
  align-items: center;
  padding: 0.4rem 0.8rem;
  background-color: #E0F2FE;
  border-radius: 6px;
  color: #0284C7;
  font-size: 0.9rem;
  margin-top: 0.5rem;
  cursor: default;
}

.message-text .tool-button .tool-icon {
  margin-right: 0.4rem;
}

.message-text .tool-tag {
  display: inline-flex;
  align-items: center;
  padding: 0.4rem 0.8rem;
  background-color: #E0F2FE;
  border-radius: 6px;
  color: #0284C7;
  font-size: 0.9rem;
  margin-top: 0.5rem;
  cursor: default;
  border: 1px solid #93C5FD;
}

.message-text .tool-tag .tool-icon {
  margin-right: 0.5rem;
}

.message-text .tool-tag .tool-name {
  font-weight: 500;
}

.selected-workflow {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.workflow-button {
  display: flex;
  align-items: center;
  padding: 0.5rem 0.8rem;
  background-color: #F0F9FF;
  border-radius: 6px;
  color: #0369A1;
  font-size: 0.9rem;
  border-left: 3px solid #3B82F6;
  position: relative;
  border: 1px solid #E2E8F0;
}

.workflow-button .workflow-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  background: linear-gradient(135deg, #3B82F6, #60A5FA);
  color: white;
  margin-right: 0.5rem;
}

.workflow-button .el-icon {
  font-size: 0.9rem;
}

.remove-workflow {
  cursor: pointer;
  color: #94A3B8;
  transition: color 0.2s ease;
}

.remove-workflow:hover {
  color: #EF4444;
}

.message-text .workflow-tag {
  display: inline-flex;
  align-items: center;
  padding: 0.4rem 0.8rem;
  background-color: #EFF6FF;
  border-radius: 6px;
  color: #1E40AF;
  font-size: 0.9rem;
  margin-top: 0.5rem;
  cursor: default;
  border-left: 3px solid #3B82F6;
}

.message-text .workflow-tag .workflow-icon:before {
  content: "🔄";
  margin-right: 0.4rem;
}

.message-text .workflow-tag .workflow-name {
  font-weight: 500;
}

.selected-item {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.8rem;
  padding: 0.5rem;
  background-color: #F8FAFC;
  border-radius: 8px;
  border: 1px dashed #CBD5E1;
}

.remove-single-item {
  cursor: pointer;
  color: #94A3B8;
  margin-left: 0.5rem;
  font-size: 0.8rem;
  transition: color 0.2s ease;
}

.remove-single-item:hover {
  color: #EF4444;
}

.remove-all-items {
  cursor: pointer;
  color: #94A3B8;
  margin-left: auto;
  padding: 0.3rem;
  border-radius: 4px;
  background-color: #FEF2F2;
  transition: all 0.2s ease;
}

.remove-all-items:hover {
  color: #EF4444;
  background-color: #FEE2E2;
}

.mcp-tool-button {
  display: flex;
  align-items: center;
  padding: 0.5rem 0.8rem;
  background-color: #F0FDF9;
  border-radius: 6px;
  color: #047857;
  font-size: 0.9rem;
  border-left: 3px solid #10B981;
  position: relative;
  border: 1px solid #E2E8F0;
}

.mcp-tool-button .mcp-tool-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  background: linear-gradient(135deg, #10B981, #34D399);
  color: white;
  margin-right: 0.5rem;
}

.mcp-tool-button .el-icon {
  font-size: 0.9rem;
}

.message-text .mcp-tool-tag {
  display: inline-flex;
  align-items: center;
  padding: 0.4rem 0.8rem;
  background-color: #ECFDF5;
  border-radius: 6px;
  color: #047857;
  font-size: 0.9rem;
  margin-top: 0.5rem;
  cursor: default;
  border-left: 3px solid #10B981;
}

.message-text .mcp-tool-tag .mcp-tool-type {
  background-color: #D1FAE5;
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  font-size: 0.7rem;
  margin-right: 0.5rem;
  color: #065F46;
}

.message-text .mcp-tool-tag .mcp-tool-name {
  font-weight: 500;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5rem;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  color: #6366F1;
  font-size: 0.9rem;
  animation: pulse 2s infinite;
}

.dots {
  display: flex;
  margin-left: 6px;
}

.dots span {
  width: 6px;
  height: 6px;
  margin: 0 2px;
  background-color: #6366F1;
  border-radius: 50%;
  display: inline-block;
  animation: dot-pulse 1.5s infinite ease-in-out;
}

.dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes pulse {
  0% {
    opacity: 0.7;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.7;
  }
}

@keyframes dot-pulse {

  0%,
  100% {
    transform: scale(0.8);
    opacity: 0.7;
  }

  50% {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 修改结果消息样式，确保流式更新时样式正确 */
.result-message {
  display: flex;
  margin-bottom: 1.2rem;
  max-width: 80%;
  animation: fadeIn 0.3s ease-out;
  align-self: flex-start;
}

.result-content-wrapper {
  background-color: #FFF8F1;
  padding: 0.9rem 1.2rem;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.06);
  position: relative;
  overflow: hidden;
  border: 1px solid #FED7AA;
}

.result-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
  color: #C2410C;
  font-weight: 500;
}

.result-header .el-icon {
  margin-right: 0.5rem;
}

.result-content {
  color: #1F2937;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  max-width: 800px; 
  min-width: 200px;
}

.result-time {
  margin-top: 0.5rem;
  font-size: 0.75rem;
  color: #94A3B8;
  text-align: right;
}
</style>